import Vue from 'vue'
import Router from 'vue-router'
import {Message} from "element-ui";

Vue.use(Router)

const router = new Router({
  mode: 'history', //去掉url中的#
  routes: [
    {
      path: '/',
      component: () => import('@/views/login/index')
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/index')
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import('@/views/home/index'),
      meta: {
        isToken: true
      },
      children: [
        {
          path: "/userList",
          name: 'userList',
          meta: {
            isToken: true
          },
          component: () => import('@/views/user/index')
        },
        {
          path: "/blogList",
          name: 'blogList',
          meta: {
            isToken: true
          },
          component: () => import('@/views/blog/index'),
        },
        {
          path: "/linkList",
          name: 'linkList',
          meta: {
            isToken: true
          },
          component: () => import('@/views/link/index')
        },
        {
          path: '/creation/editor',
          name: 'creationEditor',
          meta: {
            isToken: true
          },
          component: () =>  import('@/views/blog/creationEditor')
        },
        {
          path: "/blogDetail/:id",
          name: "blogDetail",
          props: true,
          meta: {
            isToken: true
          },
          component: () => import('@/views/blog/blogDetail')
        },
        {
          path: "/blogRecycle",
          name: "blogRecycle",
          meta: {
            isToken: true
          },
          component: () => import('@/views/recycle/blogRecycle')
        }
      ]
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/register/index')
    },
  ]
})

// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登陆
router.beforeEach((to, from, next) => {
  if(to.matched.some(record => record.meta.isToken)){
    const token = localStorage.getItem("token")
    if(token){
      if(to.path === '/login'){

      } else {
        next()
      }
    } else {
      Message.error('检测到您还未登录，请先登录谢谢！！！'),
        next({
          path: '/login'
        })
    }
  }else {
    next()
  }
});

export default router;


